#pragma
#include"RBTree.h"
#include<iostream>

namespace my_Map
{
	template<class K, class V>
	class Map
	{
		//仿函数
		struct MapKeyOfT
		{
			const K& operator()(const pair<const K, V>& kv)
			{
				return kv.first;
			}
		};

	public:
		//迭代器
		typedef typename RBTree<K, pair<const K, V>, MapKeyOfT>::iterator iterator;
		typedef typename RBTree<K, pair<const K, V>, MapKeyOfT>::const_iterator const_iterator;

		iterator begin()
		{
			return _t.begin();
		}

		iterator end()
		{
			return _t.end();
		}

		pair<iterator, bool> insert(const pair<const K, V>& kv)
		{
			return _t.Insert(kv);
		}

		//[]的实现
		V& operator[](const K& key)
		{
			pair<iterator, bool> ret = _t.Insert(make_pair(key, V()));
			return ret.first->second;
		}

	private:
		RBTree<K, pair<const K, V>, MapKeyOfT> _t;
	};

	void testMap1()
	{
		Map<string, string> m;
		m.insert(make_pair("string", "字符串"));
		m.insert(make_pair("arr", "数组"));
		m.insert(make_pair("point", "指针"));
		m.insert(make_pair("string", "(字符串)")); //插入失败

		Map<string, string>::iterator it = m.begin();
		while (it != m.end())
		{
			cout << it->first << ":" << it->second << endl;
			++it;
		}

		for (auto s : m)
		{
			cout << s.first << ":" << s.second << endl;
		}

	}
	void testMap2()
	{
		string strs[] = { "苹果", "西瓜", "苹果", "樱桃", "苹果", "樱桃", "苹果", "樱桃", "苹果" };
		// 统计水果出现的次
		Map<string, int> m;
		for (auto e : strs)
		{
			m[e]++;
		}

		for (auto e : m)
		{
			cout << e.first << ":" << e.second << endl;
		}
	}
}